<template>
    <div class="ml-16px mr-16px content-container">
        <div class="flex flex-center pt-30px pb-15px">
            <div class="flex steps">
                <div class="item" :class="{ 'step': state.stepIndex.includes(index)}" v-for="(item, index) in state.steps"
                    :key="index">
                    <p v-html="item.title"></p>
                    <span>{{ item.txt }}</span>
                </div>
            </div>
        </div>
        <div class="px-26px">
            <el-divider />
        </div>
        <div v-if="state.step === 0">
            <Step1 :model-value="state.step" :rule-form="ruleForm" :editor="'editorAdd'" @update:model-value="handleStep" />
        </div>
        <div v-if="state.step === 1">
            <Step2 :model-value="state.step" :rule-form="ruleForm" @update:model-value="handleStep" @step-2-complete="handleStep2Data" />
        </div>
        <div v-if="state.step === 2">
            <Step3 :model-value="state.step" @update:model-value="handleStep" />
        </div>
    </div>
</template>

<script setup lang="ts">
import { WarningFilled,CircleCloseFilled, SuccessFilled } from '@element-plus/icons-vue'
import { importProductApi,addProductApi,getProductWordsApi } from '@/api/b2b'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { convertWord } from '@/utils/index'
import Step1 from './components/Step-1.vue'
import Step2 from './components/Step-2.vue'
import Step3 from './components/Step-3.vue'

const router = useRouter()

const state = reactive({
    step: 0,
    steps: [
        {
            title: '第<b>1</b>步',
            txt: '填写产品信息'
        },
        {
            title: '第<b>2</b>步',
            txt: '填写产品关键词'
        },
        {
            title: '第<b>3</b>步',
            txt: '提交成功'
        }
    ],
    stepIndex:[0],
    isAdd:false
    
})

const ruleForm = reactive({
    name: '',
    model: '',
    brand: '',
    province: '',
    city: '',
    area:'',
    intro: '',
    content:'',
    mainWords:[],
    keyword:'',
    frontWords: [],
    frontWord:'',
    backWords: [],
    backWord:'',
    cusKeyword:'',
    deleteWord:'',
    cityKey: '',
    images: [
        {
            url: ''
        },
        {
            url: ''
        },
        {
            url: ''
        },
        {
            url: ''
        },
        {
            url: ''
        },
    ],
    checkStr:''
})


async function handleImport() {
    try {
        const res = await importProductApi()
        if(res.code === 200){
            state.isAdd = true
            getProductWords()
        }
    } catch (error: any) {
        state.isAdd = false
        confirmMessageBox(WarningFilled, error.response.data.message, '','',() => {
            router.go(-1)
        }, () => {
            router.go(-1)
        })
    }
}

async function handleStep2Data(value: any){
    console.log(value)
    //1 转换数据（省份+城市 = 地区）
    //2 验证表单信息 - 必删词 + 敏感词
    //3 以上成功后提交表单信息
    try{
        const res:ResType = await addProductApi({
            InforTitle:ruleForm.name,
            InforModel:ruleForm.model,
            BrandName:ruleForm.brand,
            InforOrigin:ruleForm.province + '/' + ruleForm.city,
            Description:ruleForm.intro,
            InforPicTure:ruleForm.images[0].url,
            InforPicTure2:ruleForm.images[1].url,
            InforPicTure3:ruleForm.images[2].url,
            InforPicTure4:ruleForm.images[3].url,
            InforPicTure5:ruleForm.images[4].url,
            InforContent:ruleForm.content,
            Keyword:convertWord(ruleForm.mainWords),
            LKeyword:convertWord(ruleForm.frontWords),
            RKeyword:convertWord(ruleForm.backWords),
            CusKeyword:ruleForm.cusKeyword,
            Region:ruleForm.area,
            DeleteKeyword:ruleForm.deleteWord.endsWith("/") ? ruleForm.deleteWord.slice(0, -1) : ruleForm.deleteWord //去除字符串末尾的斜杠
        })
        if(res.code === 200){
            state.step = 2
            state.stepIndex.push(2)
            reset()
        }
    }catch(error:any){
        confirmMessageBox(CircleCloseFilled, error.response.data.message)
    }
}

async function getProductWords(){
    try{
        const res:ResType = await getProductWordsApi()
        ruleForm.frontWords = res.leftkeydata
        ruleForm.backWords = res.rightkeydata
    }catch(error:any){
        confirmMessageBox(WarningFilled, error.response.data.message,'','',() => {
            router.push({
                path: '/b2b/product/list',
            })
        })
    }
}

async function reset(){
    getProductWords()     //重置词
    ruleForm.name = ''
    ruleForm.model = ''
    ruleForm.brand = ''
    ruleForm.province = ''
    ruleForm.city = ''
    ruleForm.intro = ''
    ruleForm.images[0].url = ''
    ruleForm.images[1].url = ''
    ruleForm.images[2].url = ''
    ruleForm.images[3].url = ''
    ruleForm.images[4].url = ''
    ruleForm.content = '',
    ruleForm.keyword = ''
    ruleForm.cusKeyword = 
    ruleForm.area = ''
    ruleForm.checkStr = ''
    ruleForm.deleteWord = ''
}

function handleStep(val:number){
    // 找到要删除项的索引
    let index = state.stepIndex.findIndex(item => item === val);
    if (index !== -1) {
        state.step = val - 1
        state.stepIndex.splice(index, 1); // 从索引处删除一个元素
    }else{
        state.stepIndex.push(val)
        state.step = val
    }
    if(val === 2){
        state.step = 1
        state.stepIndex = [0,1]
    }
    if(val === 0){
        state.step = 0
        state.stepIndex = [0]
    }
}

onMounted(() => {
    handleImport()
    if(state.isAdd){
        getProductWords()
    }
})


onActivated(() => {
  console.log('组件被激活（可能是从缓存恢复）')
})

onDeactivated(() => {
  console.log('组件被停用（可能被缓存或销毁）')
})
</script>

<style lang="scss" scoped>
:deep(.el-checkbox-group) {
    display: flex;
    flex-direction: column;
}
</style>